package com.cskaoyan.service.wx;

import com.cskaoyan.bean.Keyword;
import com.cskaoyan.bean.KeywordExample;
import com.cskaoyan.bean.SearchHistory;
import com.cskaoyan.bean.SearchHistoryExample;
import com.cskaoyan.bean.wx.HistoryKeywordVo;
import com.cskaoyan.bean.wx.WxSearchIndex;
import com.cskaoyan.mapper.KeywordMapper;
import com.cskaoyan.mapper.SearchHistoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class WxSearchServiceImpl implements WxSearchService {

    @Autowired
    KeywordMapper keywordMapper;
    @Autowired
    SearchHistoryMapper searchHistoryMapper;

    @Override
    public WxSearchIndex searchIndex(Integer userId) {
        KeywordExample keywordExample = new KeywordExample();
        KeywordExample.Criteria criteria = keywordExample.createCriteria();
        criteria.andIsHotEqualTo(true);
        List<Keyword> hotKeywordList = keywordMapper.selectByExample(keywordExample);
        WxSearchIndex wxSearchIndex = new WxSearchIndex();
        if (hotKeywordList != null){
            wxSearchIndex.setDefaultKeyword(hotKeywordList.get(0));
            wxSearchIndex.setHotKeywordList(hotKeywordList);
        }
        SearchHistoryExample searchHistoryExample = new SearchHistoryExample();
        List<SearchHistory> searchHistoryList = searchHistoryMapper.selectByExample(searchHistoryExample);
        if (searchHistoryList != null) {
            List<HistoryKeywordVo> historyKeywordVos = new ArrayList<>();
            for (SearchHistory searchHistory : searchHistoryList) {
                historyKeywordVos.add(new HistoryKeywordVo(searchHistory.getKeyword()));
            }
            wxSearchIndex.setHistoryKeywordList(historyKeywordVos);
        }

        return wxSearchIndex;
    }

    @Override
    public List<String> searchHelper(String keyword) {
        SearchHistoryExample searchHistoryExample = new SearchHistoryExample();
        SearchHistoryExample.Criteria criteria = searchHistoryExample.createCriteria();
        criteria.andKeywordLike("%" + keyword + "%");
        List<SearchHistory> searchHistoryList = searchHistoryMapper.selectByExample(searchHistoryExample);
        List<String> list = new ArrayList<>();
        for (SearchHistory searchHistory : searchHistoryList) {
            list.add(searchHistory.getKeyword());
        }
        return list;
    }

    @Override
    public void searchClearHistory() {
        SearchHistoryExample searchHistoryExample = new SearchHistoryExample();
        SearchHistoryExample.Criteria criteria = searchHistoryExample.createCriteria();
        searchHistoryMapper.deleteByExample(searchHistoryExample);
    }
}
